#include "sprite_explosion.h"

extern QVector<int> *vect_exp_count;

SPRITE_EXPLOSION::SPRITE_EXPLOSION(QPointF point, CASH *cash, int explosion_id, QGraphicsItem *parent) :
    QGraphicsObject(parent)
{
    vect_pix = new QVector<QPixmap*>();

    this->exp_id = explosion_id;
    this->cash = cash;
    index = 0;

    load();

    this->setPos(point);

    connect(this, SIGNAL(finished()), this, SLOT(slot_anim_finished()));

    start();
}

QRectF SPRITE_EXPLOSION::boundingRect() const
{
    if(!vect_pix->isEmpty())
        return QRectF(0, 0, vect_pix->at(index)->size().width(), vect_pix->at(index)->size().height());
    else
        return QRectF(0, 0, 10, 10);
}


void SPRITE_EXPLOSION::start()
{
    index = 0;
    timer_id = this->startTimer(50);
    emit started();
}

void SPRITE_EXPLOSION::stop()
{
    this->killTimer(timer_id);
    emit stoped();
}

void SPRITE_EXPLOSION::slot_run()
{
    this->setPos(this->pos().x(), this->pos().y() + 10);
}


void SPRITE_EXPLOSION::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
    painter->save();
    painter->drawPixmap(0, 0, *vect_pix->at(index));
    painter->restore();
}

void SPRITE_EXPLOSION::timerEvent(QTimerEvent *)
{
    if(index > vect_pix->count() - 2)
    {
        this->stop();
        emit finished();
        return;
    }

    ++index;
    this->update();
}

void SPRITE_EXPLOSION::load()
{
    for(int i=0;i<vect_exp_count->at(exp_id) - 1;i++){
        vect_pix->append(cash->cash_pixmap->value("Res/explosions/png/" + QString::number(exp_id) + "/" + QString::number(i) + ".png"));
    }
}


QPainterPath SPRITE_EXPLOSION::shape() const
{
    return QPainterPath();
}

void SPRITE_EXPLOSION::slot_anim_finished()
{
    this->setVisible(false);
    this->deleteLater();
}
